package com.yanwq.sayhi.service;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 作者：yanweiqiang。
 * 日期：2016/1/28。
 */
@Service
public class OSSService extends AbsCSService {

    String endpoint = "oss-cn-qingdao.aliyuncs.com";
    String accessKeyId = "VkJOX5zXGagsOM4p";
    String accessKeySecret = "F0yhw1Se8ohLRgwyv8zcvsU3HsehVZ";
    private String mBucket = "sayhi-yanwq";
    private OSSClient mClient;

    public OSSService() {
        // Create a new client configuration instance
        ClientConfiguration conf = new ClientConfiguration();
        // Set the maximum number of allowed open HTTP connections
        conf.setMaxConnections(100);
        // Set the amount of time to wait (in milliseconds) when initially establishing
        // a connection before giving up and timing out
        conf.setConnectionTimeout(5000);
        // Set the maximum number of retry attempts for failed retryable requests
        conf.setMaxErrorRetry(3);
        // Set the amount of time to wait (in milliseconds) for data to betransfered over
        // an established connection before the connection times out and is closed
        conf.setSocketTimeout(2000);
        // Do some operations with the instance...

        // Create a new OSSClient instance
        mClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf);
        // Shutdown the instance to release any allocated resources
    }

    public String uploadPicture(File file) throws FileNotFoundException {
        String uuid = UUID.randomUUID()
                .toString();

        InputStream inputStream = new FileInputStream(file);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.length());
        metadata.setContentType("image/jpeg");
        metadata.setContentEncoding("utf-8");
        PutObjectResult result = mClient.putObject(mBucket,
                uuid,
                inputStream,
                metadata);

        if (!file.delete()) {
            return null;
        }

        if (result != null) {
            return getURL(uuid);
        }

        return null;
    }

    public String uploadFile(File file) throws
            FileNotFoundException {
        String uuid = UUID.randomUUID()
                .toString();

        InputStream inputStream = new FileInputStream(file);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.length());
        metadata.setContentEncoding("utf-8");
        PutObjectResult result = mClient.putObject(mBucket,
                uuid,
                inputStream,
                metadata);

        //noinspection ResultOfMethodCallIgnored
        file.delete();

        if (result != null) {
            return getURL(uuid);
        }

        return null;
    }

    public void remove(String key) {
        mClient.deleteObject(mBucket, key);
    }

    public String getURL(String key) {
        return mClient.getEndpoint()
                .toString()
                .replace("http://",
                        "http://".concat(mBucket)
                                .concat("."))
                .concat("/")
                .concat(key);
    }
}
